package org.example.springbootproject.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.example.springbootproject.config.KaptchaUtil;
import org.example.springbootproject.dto.LoginRequest;
import org.example.springbootproject.dto.PaperDetailDTO;
import org.example.springbootproject.dto.RegisterRequest;
import org.example.springbootproject.entity.*;
import org.example.springbootproject.service.ExamService;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/exam")
public class ExamController {

    @Autowired
    private ExamService examService;

    @Autowired
    private KaptchaUtil kaptchaUtil;

    // ================== 试卷管理 ==================
    @GetMapping("/papers")
    public List<ExamPaper> getAllPapers() {
        return examService.getAllPapers();
    }

    @GetMapping("/papers/{id}")
    public ExamPaper getPaper(@PathVariable Long id) {
        return examService.getPaperById(id);
    }

    @PostMapping("/papers")
    public void createPaper(@RequestBody ExamPaper examPaper) {
        examService.createPaper(examPaper);
    }

    @PutMapping("/papers/{id}")
    public void updatePaper(@PathVariable Long id, @RequestBody ExamPaper paper) {
        paper.setId(id);
        examService.updatePaper(paper);
    }

    @DeleteMapping("/papers/{id}")
    public void deletePaper(@PathVariable Long id) {
        examService.deletePaper(id);
    }

    @GetMapping("/papers/{paperId}/details")
    public PaperDetailDTO getPaperDetails(@PathVariable Long paperId) {
        return examService.getPaperDetailsWithQuestions(paperId);
    }


    // ================== 出题规则管理 ==================
    @PostMapping("/rules/full")
    public void addFullRule(@RequestBody ExamRule examRule) {
        examService.createExamRule(examRule);
    }

    @GetMapping("/rules/full")
    public List<ExamRule> getFullRules() {
        return examService.getAllExamRules();
    }

    @GetMapping("/rules/full/{ruleId}")
    public ExamRule getFullRule(@PathVariable Long ruleId) {
        return examService.getExamRuleById(ruleId);
    }

    @PutMapping("/rules/full/{ruleId}")
    public void updateFullRule(
            @PathVariable Long ruleId,
            @RequestBody ExamRule examRule) {

        examRule.setId(ruleId);
        examService.updateExamRule(examRule);
    }

    @DeleteMapping("/rules/full/{ruleId}")
    public void deleteFullRule(@PathVariable Long ruleId) {
        examService.deleteExamRule(ruleId);
    }

    // ================== 题库管理 ==================
    @GetMapping("/banks")
    public List<QuestionBank> getAllBanks() {
        return examService.getAllBanks();
    }

    @GetMapping("/banks/{id}")
    public QuestionBank getBank(@PathVariable Long id) {
        return examService.getBankById(id);
    }

    @PostMapping("/banks")
    public void addBank(@RequestBody QuestionBank bank) {
        examService.addBank(bank);
    }

    @DeleteMapping("/banks/{id}")
    public void deleteBank(@PathVariable Long id) {
        examService.deleteBank(id);
    }

    @PutMapping("/banks/{id}")
    public void updateBank(@PathVariable Long id, @RequestBody QuestionBank bank) {
        bank.setId(id);
        examService.updateBank(bank);
    }

    @GetMapping("/banks/search")
    public List<QuestionBank> searchBanks(@RequestParam Map<String, String> criteria) {
        return examService.searchBanks(criteria);
    }

    // ================== 题目管理 ==================
    @GetMapping("/questions/all")
    public List<Question> getAllQuestions() {
        return examService.getAllQuestions();
    }

    @GetMapping("/questions")
    public List<Question> getQuestions(@RequestParam(required = false) Long bankId,
                                       @RequestParam(required = false) String type) {
        return examService.getQuestionsByBankAndType(bankId, type);
    }

    @PostMapping("/questions")
    public void addQuestion(@RequestBody Question question) {
        examService.addQuestion(question);
    }

    @DeleteMapping("/questions/{id}")
    public void deleteQuestion(@PathVariable Long id) {
        examService.deleteQuestion(id);
    }

    @PutMapping("/questions/{id}")
    public void updateQuestion(@PathVariable Long id, @RequestBody Question question) {
        question.setId(id);
        examService.updateQuestion(question);
    }

    @GetMapping("/questions/search")
    public List<Question> searchQuestions(@RequestParam Map<String, String> criteria) {
        return examService.searchQuestions(criteria);
    }

    // ================== 用户管理 ==================
    @PutMapping("/users/{id}")
    public void updateUser(@PathVariable Long id, @RequestBody User user) {
        examService.updateUser(id, user);
    }

    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
        examService.deleteUser(id);
    }

    @GetMapping("/users/me")
    public User getCurrentUser(HttpServletRequest request) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization").substring(7);
        return examService.getCurrentUser(token);
    }

    @GetMapping("/users")
    public List<User> getAllUsers(){
        return examService.getAllUsers();
    }

    @GetMapping("/captcha")
    public ResponseEntity<Map<String, String>> getCaptcha() {
        Map<String, String> captchaResponse = kaptchaUtil.generateBase64Captcha();
        return ResponseEntity.ok(captchaResponse);
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginRequest request, HttpServletRequest servletRequest) {
        String ip = servletRequest.getRemoteAddr();
        return examService.login(request.getUsername(), request.getPassword(), request.getCaptcha(), request.getImgToken(), ip);
    }


    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody RegisterRequest request, HttpServletRequest servletRequest) {
        String ip = servletRequest.getRemoteAddr();
        examService.register(request.getUsername(), request.getPassword(), ip);
        return Map.of("message", "注册成功");
    }
}